import io
import json
import logging
import random

import re
from django.contrib import auth
from django.contrib.auth import login, logout
from django.http import HttpResponse, JsonResponse
from django.views import View
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.users.models import User
from libs.captcha.captcha import captcha
from utils.center_user import LoginRequiredJSONMixin
from utils.mei_email import check_token
# 这是用户的校验是否存在
class UsernameView(APIView):
    def get(self, request, name):
        count = User.objects.filter(username=name).count()
        return Response({'code': 0, 'errmsg': 'ok', 'count': count})


# 这是手机号的校验是否存在
class MobileView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return Response({'code': 0, 'errmsg': 'ok', 'count': count})


# 这是我们第三包captcha获取到生成的图片验证码
class Image(APIView):
    def get(self, request, image_code_id):
        # 进行调用获取生成我们的图片验证码和uuid
        image_code, image = captcha.generate_captcha()
        # 然后进行使用我们的django_redis来进行设置键的属性和过期时间
        redis_client = get_redis_connection('code')
        redis_client.setex(image_code_id, 300, image_code)
        # 便于查询我们生成的图片验证码，我们进行查看我们的日志记录，可以查询的到图片验证码的详细信息
        logger = logging.getLogger('django')
        logger.info(image_code)
        # 然后返回响应，给前端，类型为jpeg
        return HttpResponse(image, content_type='image/jpeg')




# 这是我们发送短信验证码，和验证码校验的视图
class Send_messageView(APIView):
    def get(self, request, mobile):
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({'message': '手机号不符合规范'}, status=400)
        a2 = get_redis_connection().get(mobile)
        if a2 is not None:
            return Response({'message': '验证码已存在，请勿重复发送'}, status=400)
        image_code = request.GET.get('image_code')
        image_code_id = request.GET.get('image_code_id')
        a1 = get_redis_connection('code').get(image_code_id)
        if a1 is None:
            return Response({'message': '图片验证码过期'}, status=400)
        if a1.decode('utf8').lower() != image_code.lower():
            return Response({'message': '图片验证码错误'}, status=400)
        code = str(random.randint(1000, 9999))
        loger = logging.getLogger('django')
        loger.info(code)
        bb = get_redis_connection()
        bb.set(mobile, code, 60)
        from celery_tasks.sms.tasks import send_code
        # send_code.delay(mobile, code)
        return Response({'code': 0})

# 这是我们注册的视图，以及前端参数的校验
class Register(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        password2 = request.data.get('password2')
        mobile = request.data.get('mobile')
        sms_code = request.data.get('sms_code')
        allow = request.data.get('allow')
        if not all([username, password, password2, mobile, allow]):
            return Response({'code': 400, 'errmsg': '缺少必传参数!'})
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return Response({'code': 400, 'errmsg': 'username格式有误!'})
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return Response({'code': 400, 'errmsg': 'password格式有误!'})
        # 判断两次密码是否一致
        if password != password2:
            return Response({'code': 400, 'errmsg': '两次输入不对!'})
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({'code': 400, 'errmsg': 'mobile格式有误!'})
        # 判断是否勾选用户协议
        if allow != True:
            return Response({'code': 400, 'errmsg': 'allow格式有误!'})
        r = get_redis_connection().get(mobile)
        if r is None:
            return Response({'code': 400, 'errmsg': '验证码错误'})
        if r.decode('utf8') != sms_code:
            return Response({'code': 400, 'errmsg': '手机验证码错误'})
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except:
            return Response({'code': 400, 'errmsg': '注册失败'})
        login(request, user)
        a1 = Response({'code': 0, 'errmsg': 'ok'})
        a1.set_cookie('username', username)
        return a1

# 这是我们的登录视图
class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        rememberd = request.data.get('rememberd')
        if not all((username, password)):
            return Response({'code': 400, 'errmsg': '参数不全'})
        if re.match(r'^1[3-9]\d{9}$', username):
            User.USERNAME_FIELD = 'mobile'
        user = auth.authenticate(username=username, password=password)
        if not user:
            User.USERNAME_FIELD = 'username'
            user = auth.authenticate(username=username, password=password)
            if not user:
                return Response({'code': 400, 'errmsg': '账号或密码错误'})
        if not rememberd:
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)
        login(request, user)
        a1 = Response({'code': 0, 'errmsg': 'ok'})
        a1.set_cookie('username', username)
        return a1



# 这是我们退出登录的视图
class LogoutView(View):
    def delete(self, request):
        logout(request)
        a1 = JsonResponse({'code': 0, 'errmsg': 'ok'})
        a1.delete_cookie('username')
        return a1


# 这是我们用户中心的视图
class CenterView(LoginRequiredJSONMixin, View):
    def get(self, request):
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            "email": request.user.email,
            'email_active': request.user.email_active
        }
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_data})



# 这是我们发送邮箱以及加密邮箱验证码的视图
class EmailView(LoginRequiredJSONMixin, View):
    def put(self, request):
        data = json.loads(request.body)
        email = data.get('email')
        request.user.email = email
        request.user.save()
        from utils.mei_email import  generate_active_email
        verify_url = generate_active_email({'id':request.user.id,'email':email})
        from celery_tasks.email.tasks import senf_active
        senf_active.delay(verify_url = verify_url,email=email)
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


# 这是我们激活邮箱验证码的视图
class EmailVeifiView(View):
    def put(self,request):
        token = request.GET.get('token')
        data = check_token(token)
        if data is None:
            return JsonResponse({'code':400,'errmsg':'数据过期'})
        id = data.get('id')
        email =data.get('email')
        try:
           user = User.objects.get(id=id,email=email)
        except Exception as e:
             return JsonResponse({'code':400,'errmsg':'数据过期或数据错误'})
        user.email_active=True
        user.save()
        return JsonResponse({'code':0,'errmsg':'ok'})






